package com.project.controller.login;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.project.entity.sys.User;
import com.project.service.sys.UserService;
import com.project.util.EncryptString;
import com.project.util.VerifyCodeUtil;

@Controller
@RequestMapping("/login")
public class LoginController{
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="init",method=RequestMethod.GET)
	public String login(Model model){
		return "/login";
	}
	
	/** 
     * 获取验证码图片和文本(验证码文本会保存在HttpSession中) 
     */  
    @RequestMapping("getVerifyCodeImage")  
    public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {  
        //设置页面不缓存  
        response.setHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);  
        //将验证码放到HttpSession里面  
        logger.info("验证码============{}",verifyCode);
        request.getSession().setAttribute("verifyCode", verifyCode);  
//        System.out.println("本次生成的验证码为[" + verifyCode + "],已存放到HttpSession中");  
        //设置输出的内容的类型为JPEG图像  
        response.setContentType("image/jpeg");  
        BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);  
        //写给浏览器  
        ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());  
    }  
    
    @RequestMapping(value="/doLogin",method=RequestMethod.POST)
    public String login(HttpServletRequest request, Model model) throws Exception {
    	logger.info("进入登录验证");
       // 登录失败从request中获取shiro处理的异常信息。
       // shiroLoginFailure:就是shiro异常类的全类名.
       String resultPageURL = "/login";  
       String username = request.getParameter("username");  
       String password = request.getParameter("password");  
       String verifyCode = (String)request.getSession().getAttribute("verifyCode");  
       String submitCode = WebUtils.getCleanParam(request, "verifyCode");  
       if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(verifyCode, submitCode.toLowerCase())){  
    	   model.addAttribute("message_login", "验证码不正确");  
           return resultPageURL;  
       }
       User user = new User();
       user.setUserCode(username);;
       user = userService.queryEntity(user);
       UsernamePasswordToken token = new UsernamePasswordToken(username, EncryptString.MD5(password+user.getSalt()));  
//       UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
       token.setRememberMe(true);  
//     System.out.println("为了验证登录用户而封装的token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));  
       //获取当前的Subject  
       Subject currentUser = SecurityUtils.getSubject();  
       SecurityUtils.getSecurityManager();
       try {  
           currentUser.login(token);
           request.getSession(true).setAttribute("user", user);
           resultPageURL = "redirect:/admin/index";
       }catch(UnknownAccountException uae){ 
       	model.addAttribute("message_login", "账号不存在");  
       }catch(IncorrectCredentialsException ice){  
       	model.addAttribute("message_login", "密码错误");  
       }catch(LockedAccountException lae){  
       	model.addAttribute("message_login", "账户未启用");  
       }catch(ExcessiveAttemptsException eae){
       	model.addAttribute("message_login", "用户名或密码错误次数过多");  
       }catch(AuthenticationException ae){  
           //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景  
           //System.out.println("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");  
           ae.printStackTrace();  
           model.addAttribute("message_login", "用户名或密码不正确");  
       }  
       //验证是否登录成功  
       if(currentUser.isAuthenticated()){  
       	logger.info("用户:"+username+"登录");
//       	return "redirect:/home/home?menuUrlSign=1";
       }else{  
           token.clear();  
       }  
       return resultPageURL;
    }
    
    /** 
     * 用户登出 
     */  
    @RequestMapping("/logout")  
    public String logout(HttpServletRequest request){  
         SecurityUtils.getSubject().logout();  
         return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/";  
    } 
}
